<?php

namespace App\Models\Order;

use App\Models\Customer\Customer;
use App\Models\Video;
use App\User;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{

    const ORDER_NEW = 'new';
    const ORDER_PAY = 'pay';
    const ORDER_CAN = 'can';

    protected $table = 'order';

    protected $fillable = ['number', 'author_id', 'total', 'state'];

    protected $appends = [
        'total',
        'state'
    ];

    public function setTotalAttribute($value)
    {
        $this->attributes['total'] = intval(($value * 100));
    }

    public function getTotalAttribute($value)
    {
        return round(($this->attributes['total'] / 100), 2);
    }

    public function author()
    {
        return $this->hasOne(Customer::class, 'id', 'author_id');
    }

    public function item()
    {
        return $this->hasOne(Item::class, 'order_id', 'id');
    }

    public function getStateAttribute($value)
    {
        $state = '等待支付';
        if ($this->attributes['state'] === self::ORDER_PAY) {
            $state = '已完成';
        } elseif (self::ORDER_CAN === $this->attributes['state']) {
            $state = '已取消';
        }
        return $state;
    }

    public static function countQty(Video $video)
    {
        $orders = static::where('state', self::ORDER_PAY)->whereHas('item', function ($query) use ($video) {
            $query->where('video_id', $video->id);
        })->count();
        return $orders;
    }
}